package com.cloudptt.api.models.lbs;


public class Geo24BitConverter {
    private static final int MAX_24BIT = 0xFFFFFF; // 16,777,215
    private static final int MAX_23BIT = 0x7FFFFF; // 8,388,607 (2^23-1)

    // 编码方法
    public static int[] encode(
            double longitude,
            double latitude,
            double altitude,
            double speed,
            double bearing
    )
    {
        if(longitude < 0)
        {
            longitude = longitude + 360;
        }
        // 经度编码 (0-360° → 0-16,777,215)
        int lon = (int) (longitude / 360.0 * MAX_24BIT);

        // 纬度编码 (最高位标识南北纬)
        int latValue = (int) (Math.abs(latitude) / 90.0 * MAX_23BIT);
        int lat = (latitude >= 0) ? latValue : (1 << 23) | latValue;

        // 海拔编码 (-1000m~9000m → 0-16,777,215)
        int alt = (int) ((altitude + 1000) / 10000.0 * MAX_24BIT);

        // 速度编码 (0-1000m/s → 0-16,777,215)
        int spd = (int) (speed / 1000.0 * MAX_24BIT);

        // 方向编码 (0-360° → 0-16,777,215)
        int dir = (int) (bearing / 360.0 * MAX_24BIT);

        return new int[]{lon, lat, alt, spd, dir};
    }

    // 解码方法
    public static double[] decode(int[] encoded) {
        // 经度解码
        double lon = encoded[0] * 360.0 / MAX_24BIT;

        // 纬度解码（提取最高位判断南北）
        boolean isSouth = (encoded[1] & (1 << 23)) != 0;
        double lat = (encoded[1] & MAX_23BIT) * 90.0 / MAX_23BIT;
        if (isSouth) lat = -lat;

        // 海拔解码
        double alt = encoded[2] * 10000.0 / MAX_24BIT - 1000;

        // 速度解码
        double speed = encoded[3] * 1000.0 / MAX_24BIT;

        // 方向解码
        double bearing = encoded[4] * 360.0 / MAX_24BIT;

        return new double[]{lon, lat, alt, speed, bearing};
    }

    // 24bit整数转3字节（大端序）
    public static byte[] toBytes(int value) {
        return new byte[] {
                (byte) ((value >> 16) & 0xFF),
                (byte) ((value >> 8) & 0xFF),
                (byte) (value & 0xFF)
        };
    }
}


